package com.dp.quickStart;

import lombok.experimental.Accessors;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.List;

/**
 * @Author: dupeng
 * @CreateTime: 2024-12-23  11:27
 * @Description: TODO
 */
@Accessors
public class Demo3 {

    private RestHighLevelClient client;

    @BeforeEach
    public void before() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://152.136.59.90:9200")
        ));
    }

    @Test
    public void test() throws IOException {
        //创建查询对象
        SearchRequest searchRequest = new SearchRequest("items");

        //聚合操作
//        searchRequest.source().aggregations().addAggregator(AggregationBuilders
//                        .stats("brand").subAggregation(AggregationBuilders.terms("brand").field("brand").size(20)))
//        ;
        searchRequest.source()
                .size(0)
                .aggregation(AggregationBuilders
//                        .terms("brand_agg").field("brand").size(20)
                                .stats("price_agg").field("price")
                        );

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //解析响应
        parseResponse(response);
    }

    private void parseResponse(SearchResponse response) {
        System.out.println("以下是响应");
        System.out.println(response);
        Aggregations aggregations = response.getAggregations();
        Terms agg_brand = aggregations.get("agg_brand");
        List<? extends Terms.Bucket> buckets = agg_brand.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            System.out.println(keyAsString);
        }
    }


    @AfterEach
    public void after() throws Exception {
        client.close();
    }

}
